package com.alibaba.citrus.cr.price.adapter;

import com.alibaba.acm.shaded.com.alibaba.metrics.StringUtils;
import com.alibaba.acm.shaded.com.google.common.collect.Lists;
import com.alibaba.cz.base.tool.Nullable;
import com.alibaba.cz.base.tool.log.Log;
import com.alibaba.fastjson.JSON;
import com.alibaba.lattice2.epoch.sdk.model.Result;
import com.epoch.app.bcorder.model.dto.*;
import com.epoch.app.bcorder.service.BaseDataService;
import com.epoch.app.crpricecenter.model.dto.BatchCreditQueryRequest;
import com.epoch.app.crpricecenter.model.dto.CreditInfoSDO;
import com.epoch.app.crpricecenter.model.dto.RestSapQueryCreditRequest;
import com.epoch.app.crpricecenter.model.dto.SapCreditSDO;
import com.epoch.app.crpricecenter.service.CrPriceCenterService;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author zhoubc
 * @description: TODO
 * @date 2022/6/27 21:39
 */
@Service
public class CreditQueryAdapter {

    private static final Log log = Log.getLogger(CreditQueryAdapter.class);

    @Resource
    private BaseDataService baseDataService;

    @Resource
    CrPriceCenterService crPriceCenterService;

    /**
     * 目前的业务场景，信贷查询不会批量查询请求，，内外部主数据信息转换先不做批量查询
     * @param request
     * @return
     */
    public List<CreditInfoSDO> sapCreditQuery(BatchCreditQueryRequest request){
        if(CollectionUtils.isEmpty(request.getCreditQueryList())){
            return new ArrayList<>();
        }
        List<CreditInfoSDO> sapCreditQueryList = request.getCreditQueryList().stream().map(x-> {
            if(StringUtils.isNotBlank(x.getOrganizationCode())){
                //调用基线API获取sap的组织编码
                BaselineGetOrganizationById2Request baselineGetOrganizationById2Request = new BaselineGetOrganizationById2Request();
                baselineGetOrganizationById2Request.setId(x.getOrganizationCode());
                Result<OrganizationSDO> orgResult =  baseDataService.baselineGetOrganizationById2(baselineGetOrganizationById2Request);
                if(orgResult.getResult() != null){
                    x.setOrganizationCode(orgResult.getResult().getOutCode());
                }
            }
            if(StringUtils.isNotBlank(x.getChannelCode())){
                //调用基线API获取sap渠道编码
                BaselineBatchQueryChannels2Request baselineBatchQueryChannels2Request = new BaselineBatchQueryChannels2Request();
                baselineBatchQueryChannels2Request.setChannelCodes(Lists.newArrayList(x.getChannelCode()));
                Result<List<ChannelSDO>> channelResult = baseDataService.baselineBatchQueryChannels2(baselineBatchQueryChannels2Request);
                if(CollectionUtils.isNotEmpty(channelResult.getResult())){
                    x.setChannelCode(channelResult.getResult().get(0).getOutCode());
                }
            }
            return x;
        }).collect(Collectors.toList());
        RestSapQueryCreditRequest queryRequest = new RestSapQueryCreditRequest();
        queryRequest.setData(sapCreditQueryList);
        Result<List<SapCreditSDO>> response = crPriceCenterService.restSapQueryCredit(queryRequest);
        List<CreditInfoSDO> result = Nullable.stream(response.getResult()).map(x-> sapCreditSDO2CreditInfoConverter(x)).collect(Collectors.toList());
        return result;
    }

    public List<CreditInfoSDO> sapBatchCreditQuery(BatchCreditQueryRequest request){
        if(CollectionUtils.isEmpty(request.getCreditQueryList())){
            return new ArrayList<>();
        }
        RestSapQueryCreditRequest queryRequest = new RestSapQueryCreditRequest();
        queryRequest.setData(request.getCreditQueryList());
        log.info("CreditQueryAdapter#sapBatchCreditQuery queryRequest:{}", JSON.toJSONString(queryRequest));
        Result<List<SapCreditSDO>> response = crPriceCenterService.restSapQueryCredit(queryRequest);
        return Nullable.stream(response.getResult()).map(this::sapCreditSDO2CreditInfoConverter).collect(Collectors.toList());
    }

    private CreditInfoSDO sapCreditSDO2CreditInfoConverter(SapCreditSDO sapCreditSDO){
        CreditInfoSDO sdo = new CreditInfoSDO();
        sdo.setOrganizationCode(sapCreditSDO.getVKORG());
        sdo.setChannelCode(sapCreditSDO.getVTWEG());
        sdo.setItemGroupCode(sapCreditSDO.getSPART());
        sdo.setCustomerCode(sapCreditSDO.getKUNNR());
        sdo.setSaleOrderId(sapCreditSDO.getZVBELN());
        sdo.setRiskType(sapCreditSDO.getCTLPC());
        sdo.setCreditFlag(sapCreditSDO.getZFLAG());
        sdo.setCode(sapCreditSDO.getCODE());
        sdo.setMessage(sapCreditSDO.getMESSAGE());

        // 特殊处理， 增加对sap负值， 负号在末位的处理
        String dealBalance = StringUtils.isNotBlank(sapCreditSDO.getOBLIG()) && sapCreditSDO.getOBLIG().endsWith("-")?
                "-" + sapCreditSDO.getOBLIG().substring(0, sapCreditSDO.getOBLIG().length() - 1):sapCreditSDO.getOBLIG();
        sdo.setBalance(dealBalance);

        // 特殊处理， 增加对sap负值， 负号在末位的处理
        String feeBalance = StringUtils.isNotBlank(sapCreditSDO.getZFAMT()) && sapCreditSDO.getZFAMT().endsWith("-")?
                "-" + sapCreditSDO.getZFAMT().substring(0, sapCreditSDO.getZFAMT().length() - 1):sapCreditSDO.getZFAMT();
        sdo.setFeeBalance(feeBalance);
        return sdo;
    }

}
